import React, { useState, useEffect } from 'react';
import {
  Card,
  Button,
  Space,
  Spin,
  Typography,
  Divider,
  Alert,
  Tag,
  Tooltip,
  Row,
  Col,
  message,
  Collapse,
  List
} from 'antd';
import {
  ExperimentOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  LoadingOutlined,
  InfoCircleOutlined,
  BulbOutlined
} from '@ant-design/icons';
import {
  LLMOptimizeRequest,
  LLMOptimizationResult,
  LLMConfigResponse,
  optimizeSql,
  getLLMConfig
} from '../../services/api';
import SqlComparisonView from './SqlComparisonView';
import './LLMOptimizationPanel.css';

const { Title, Text, Paragraph } = Typography;
const { Panel } = Collapse;

interface LLMOptimizationPanelProps {
  sqlContent: string;
  sourceDbType: string;
  targetDbType: string;
  userId: number;
  visible: boolean;
}

const LLMOptimizationPanel: React.FC<LLMOptimizationPanelProps> = ({
  sqlContent,
  sourceDbType,
  targetDbType,
  userId,
  visible
}) => {
  const [llmConfig, setLlmConfig] = useState<LLMConfigResponse | null>(null);
  const [optimizationResult, setOptimizationResult] = useState<LLMOptimizationResult | null>(null);
  const [isOptimizing, setIsOptimizing] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  // 加载LLM配置
  useEffect(() => {
    if (visible && userId) {
      loadLLMConfig();
    }
  }, [visible, userId]);

  const loadLLMConfig = async () => {
    setIsLoading(true);
    try {
      const response = await getLLMConfig(userId);
      if (response.success) {
        setLlmConfig(response.data);
      } else {
        message.error(response.message || '获取LLM配置失败');
      }
    } catch (error: any) {
      console.error('加载LLM配置失败:', error);
      message.error(error.message || '加载LLM配置失败');
    } finally {
      setIsLoading(false);
    }
  };

  const handleOptimizeSql = async () => {
    if (!sqlContent.trim()) {
      message.warning('请输入SQL语句');
      return;
    }

    setIsOptimizing(true);
    try {
      const request: LLMOptimizeRequest = {
        sql: sqlContent,
        sourceDbType,
        targetDbType
      };

      const response = await optimizeSql(request, userId);
      if (response.success) {
        setOptimizationResult(response.data);
        message.success('SQL优化完成');
      } else {
        message.error(response.message || 'SQL优化失败');
      }
    } catch (error: any) {
      console.error('SQL优化失败:', error);
      message.error(error.message || 'SQL优化失败');
    } finally {
      setIsOptimizing(false);
    }
  };

  if (!visible) return null;

  if (isLoading) {
    return (
      <Card title="LLM优化分析" className="llm-optimization-panel">
        <div style={{ textAlign: 'center', padding: '40px 0' }}>
          <Spin size="large" />
          <div style={{ marginTop: 16 }}>正在加载配置...</div>
        </div>
      </Card>
    );
  }

  if (!llmConfig?.enabled) {
    return (
      <Card title="LLM优化分析" className="llm-optimization-panel">
        <Alert
          message="LLM优化功能未启用"
          description="请联系管理员启用大模型优化功能"
          type="warning"
          showIcon
        />
      </Card>
    );
  }

  return (
    <Card 
      title={
        <Space>
          <ExperimentOutlined />
          LLM优化分析
          <Tag color="blue">BETA</Tag>
        </Space>
      }
      className="llm-optimization-panel"
      extra={
        <Tooltip title="使用大模型分析SQL并提供优化建议">
          <InfoCircleOutlined style={{ color: '#1890ff' }} />
        </Tooltip>
      }
    >
      {/* 模型信息显示 */}
      <div style={{ marginBottom: 16, padding: 12, backgroundColor: '#f5f5f5', borderRadius: 4 }}>
        <Row gutter={[16, 8]}>
          <Col span={12}>
            <Text type="secondary">默认提供商:</Text>
            <br />
            <Text strong>{llmConfig.defaultProvider?.toUpperCase() || 'N/A'}</Text>
          </Col>
          <Col span={12}>
            <Text type="secondary">服务状态:</Text>
            <br />
            <Text strong style={{ color: llmConfig.enabled ? '#52c41a' : '#ff4d4f' }}>
              {llmConfig.enabled ? '已启用' : '未启用'}
            </Text>
          </Col>
        </Row>
      </div>

      {/* 操作按钮 */}
      <Space style={{ width: '100%', justifyContent: 'center', marginBottom: 16 }}>
        <Button
          type="primary"
          icon={isOptimizing ? <LoadingOutlined /> : <ExperimentOutlined />}
          onClick={handleOptimizeSql}
          loading={isOptimizing}
          disabled={!sqlContent.trim()}
          size="large"
        >
          {isOptimizing ? '分析中...' : 'LLM优化分析'}
        </Button>
      </Space>

      {/* 优化结果 */}
      {optimizationResult && (
        <>
          <Divider />
          <div className="optimization-result">
            <Title level={5}>
              <BulbOutlined style={{ color: '#52c41a', marginRight: 8 }} />
              优化结果
            </Title>

            {/* 元数据信息 */}
            <Row gutter={[16, 8]} style={{ marginBottom: 16 }}>
              <Col span={8}>
                <Text type="secondary">模型:</Text>
                <br />
                <Text>{optimizationResult.metadata.modelName}</Text>
              </Col>
              <Col span={8}>
                <Text type="secondary">处理时间:</Text>
                <br />
                <Text>{optimizationResult.metadata.processingTime}ms</Text>
              </Col>
              <Col span={8}>
                <Text type="secondary">Token使用:</Text>
                <br />
                <Text>{optimizationResult.metadata.tokensUsed || 'N/A'}</Text>
              </Col>
            </Row>

            {/* SQL对比视图 */}
            <SqlComparisonView
              originalSql={optimizationResult.originalSql}
              optimizedSql={optimizationResult.optimizedSql}
              highlights={optimizationResult.highlights}
            />

            {/* 优化说明 */}
            <Collapse style={{ marginTop: 16 }}>
              <Panel header="优化说明" key="explanation">
                <Paragraph style={{ whiteSpace: 'pre-line' }}>
                  {optimizationResult.explanation}
                </Paragraph>
              </Panel>

              {/* 详细优化建议 */}
              {optimizationResult.optimizationDetails && optimizationResult.optimizationDetails.trim() && (
                <Panel header="详细优化建议" key="optimizationDetails">
                  <div 
                    style={{ 
                      fontFamily: 'inherit',
                      lineHeight: '1.6',
                      maxHeight: '500px',
                      overflow: 'auto'
                    }}
                    dangerouslySetInnerHTML={{
                      __html: optimizationResult.optimizationDetails
                    }}
                  />
                  
                  {/* 添加表格样式 */}
                  <style>{`
                    .optimization-table {
                      width: 100%;
                      border-collapse: collapse;
                      margin-top: 16px;
                      font-size: 14px;
                      background-color: white;
                      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
                      border-radius: 6px;
                      overflow: hidden;
                    }
                    
                    .optimization-table th {
                      background-color: #fafafa;
                      border: 1px solid #d9d9d9;
                      padding: 12px;
                      text-align: left;
                      font-weight: 600;
                      color: #262626;
                      font-size: 13px;
                    }
                    
                    .optimization-table td {
                      border: 1px solid #d9d9d9;
                      padding: 12px;
                      vertical-align: top;
                      line-height: 1.5;
                    }
                    
                    .optimization-table tr:nth-child(even) {
                      background-color: #fafafa;
                    }
                    
                    .optimization-table tr:hover {
                      background-color: #e6f7ff;
                    }
                    
                    .optimization-table td:first-child {
                      text-align: center;
                      font-weight: 600;
                      width: 50px;
                    }
                    
                    .optimization-table td:nth-child(2) {
                      font-weight: 500;
                      color: #1890ff;
                      min-width: 80px;
                    }
                    
                    .optimization-table td:nth-child(3),
                    .optimization-table td:nth-child(4) {
                      font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
                      background-color: #f6f8fa;
                      color: #d73a49;
                      font-size: 12px;
                    }
                    
                    .optimization-table td:last-child {
                      text-align: center;
                      font-weight: 600;
                      min-width: 60px;
                    }
                  `}</style>
                </Panel>
              )}

              {/* 兼容性问题 */}
              {optimizationResult.issues.length > 0 && (
                <Panel header={`发现的兼容性问题 (${optimizationResult.issues.length})`} key="issues">
                  <List
                    dataSource={optimizationResult.issues}
                    renderItem={(issue, index) => (
                      <List.Item>
                        <List.Item.Meta
                          avatar={
                            issue.severity === 'HIGH' ? (
                              <ExclamationCircleOutlined style={{ color: '#ff4d4f' }} />
                            ) : issue.severity === 'MEDIUM' ? (
                              <ExclamationCircleOutlined style={{ color: '#faad14' }} />
                            ) : (
                              <InfoCircleOutlined style={{ color: '#1890ff' }} />
                            )
                          }
                          title={
                            <Space>
                              {issue.type}
                              <Tag color={
                                issue.severity === 'HIGH' ? 'red' : 
                                issue.severity === 'MEDIUM' ? 'orange' : 'blue'
                              }>
                                {issue.severity}
                              </Tag>
                            </Space>
                          }
                          description={
                            <>
                              <div>{issue.description}</div>
                              {issue.suggestion && (
                                <div style={{ color: '#1890ff', marginTop: 4 }}>
                                  💡 {issue.suggestion}
                                </div>
                              )}
                            </>
                          }
                        />
                      </List.Item>
                    )}
                  />
                </Panel>
              )}
            </Collapse>
          </div>
        </>
      )}
    </Card>
  );
};

export default LLMOptimizationPanel;